package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.UserLoginMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaoxiaode
 * @date 2021/9/23 23:23
 **/
@Service
@Slf4j
@Transactional
public class ApUserServiceImpl extends ServiceImpl<UserLoginMapper,ApUser> implements ApUserService{

    public ResponseResult login(LoginDto dto) {
        // 根据用户名获取用户信息
        if(StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            QueryWrapper<ApUser> wrapper=new QueryWrapper<>();
            wrapper.eq("phone",dto.getPhone());
            ApUser user = getOne(wrapper);
            if(user==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
            }

            // 比对密码
            String salt = user.getSalt();
            String password = dto.getPassword();
            String md5pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if(!md5pwd.equals(user.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            // 返回jwt user
            String token = AppJwtUtil.getToken(user.getId().longValue());
            Map<String,Object> map=new HashMap<>();
            map.put("token",token);
            user.setSalt("");
            user.setPassword("");
            map.put("user",user);
            System.out.println(user);
            return ResponseResult.okResult(map);
        }else{
            // 游客登录
            Map<String,Object> map=new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return  ResponseResult.okResult(map);
        }

    }
}
